package com.macasa.panel.web.auth.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.macasa.panel.web.auth.api.AuthenticationService;

@Service("authenticationService")
@Scope("singleton")
public class AuthenticationServiceImpl implements AuthenticationService {

	@Autowired
	@Qualifier("authenticationManager")
	private AuthenticationManager	authenticationManager;	// specific for Spring Security

	@Override
	public boolean login(final String username, final String password) {
		try {
			final Authentication authenticate = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
			if (authenticate.isAuthenticated()) {
				SecurityContextHolder.getContext().setAuthentication(authenticate);
				return true;
			}
		} catch (final AuthenticationException e) {
			/**
			 * TODO : voir quoi faire ici
			 */
		}
		return false;
	}

	@Override
	public void logout() {
		SecurityContextHolder.getContext().setAuthentication(null);
	}

	/**
	 * @return the authenticationManager
	 */
	public final AuthenticationManager getAuthenticationManager() {
		return this.authenticationManager;
	}

	/**
	 * @param authenticationManager
	 *            the authenticationManager to set
	 */
	public final void setAuthenticationManager(final AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

}
